package controller;

import utils.MutableInteger;
import utils.PlayerSides.Sides;
import view.ViewController;

/**
 * Class used to determine if a computer-controlled game should end 
 */
public class ComputerGameTerminator implements GameTerminator {

	private static final int MAX_TURNS = 30; // maximal number of turns for a game
	private KingThreat threatAnalyzer; // used to verify game end state
	private ViewController view; // used to for user notifications
	private MutableInteger turnCounter; // counts turns in current game
	
	/**
	 * Constructor- creates a new game terminator for computer-controlled game
	 * @param threatAnalyzer- verifies game ending states
	 * @param view- notifies user
	 * @param turnCounter- counts turns in current game
	 */
	public ComputerGameTerminator(KingThreat threatAnalyzer, ViewController view, MutableInteger turnCounter) {
		
		// set members according to given values
		this.threatAnalyzer = threatAnalyzer;
		this.view = view;
		this.turnCounter = turnCounter;
	}

	/**
	 * Ends game if game has reached Checkmate or Stalemate or if
	 * reached maximal number of turns
	 */
	@Override
	public boolean isGameOver(Sides currPlayerSide) {
		
		// check if reached maximal number of turns
		if (turnCounter.get() >= MAX_TURNS) {
			// notify user
			view.notifyGameOver("Played " + turnCounter.get() + " turns");
			return true;
		}
		
		// check if Checkmate
		if (threatAnalyzer.isCheckmate(currPlayerSide)) {
			// notify user
			view.notifyGameOver("Checkmate!");
			return true;
		}
		
		// check if Stalemate
		if (threatAnalyzer.isStalemate(currPlayerSide)) {
			// notify user
			view.notifyGameOver("Stalemate!");
			return true;
		}
		
		// game is not over
		return false;
	}
}